<template>
  <Wrap>
    <splitpanes class='default-theme' style='height: 100%' v-show='state.pageShow'>
      <pane :size='state.leftPaneSize'>
        <DeptTree @node-click='nodeClick' />
      </pane>
      <pane>
        <el-card class='box-card' style='height: 100%;'>
          <template #header>
            <div class='zjustify'>
              <div>
                <el-input v-model='state.form.name' placeholder='输入名称回车查询' clearable class='list-search' @keyup.enter='listQuery(state)' />
                <el-button type='primary' @click='listQuery(state)' :icon='Search' plain>查询</el-button>
                <el-button class='more-button' :icon='state.moreParams?ArrowUp:ArrowDown' plain @click='state.moreParams=!state.moreParams' />
              </div>
              <div>
                <el-button type='success' :icon='Plus' @click='editRef.open({depid:state.form.depid,depna:state.form.depna})' plain>新增 [弹框]</el-button>
                <el-button type='success' :icon='Plus' @click='tabAdd(state.url,{depid:state.form.depid,depna:state.form.depna},{flush})' plain>
                  新增 [页签]
                </el-button>
                <el-button type='danger' :icon='Delete' :disabled='state.multiple' @click='listDelete(state)' plain>删除</el-button>
              </div>
            </div>
            <div v-show='state.moreParams' class='more-params'>
              <el-form :inline='true' label-width='100px'>
                <el-form-item label='用户工号'>
                  <el-input v-model='state.form.usnam' placeholder='用户工号' style='width:120px' />
                </el-form-item>
                <el-form-item label='用户昵称'>
                  <el-input v-model='state.form.ninam' placeholder='用户昵称' style='width:120px' />
                </el-form-item>
                <el-form-item label='手机号'>
                  <el-input v-model='state.form.monum' placeholder='手机号' style='width:120px' />
                </el-form-item>
                <el-form-item />
              </el-form>
            </div>
          </template>

          <el-table height='400' :cell-style="{padding:'2px'}" :row-style="{height: '36px'}" v-loading='state.loading' :data='state.list'
                    border stripe @selection-change='listSelect($event,state)'>
            <el-table-column type='selection' width='55' align='center' />
            <el-table-column label='序号' type='index' width='55' align='center' />
            <el-table-column label='用户名称' width='180'>
              <template #default='scope'>
                <span style='cursor:pointer;color: #3e9ece' @click='editRef.open({id:scope.row.id})'>{{ scope.row.name }}</span>
              </template>
            </el-table-column>
            <el-table-column label='备注' prop='notes' />
            <el-table-column label='创建时间' prop='crtim' width='160' />
            <el-table-column label='更新时间' prop='uptim' width='160' />
            <el-table-column label='操作' width='80' header-align='center' align='center'>
              <template #default='scope'>
                <el-icon @click='tabEdit(state.url,scope.row.id)' style='cursor: pointer;font-size: 18px;top:2px;margin-left: 11px;color: #2874C5'>
                  <Edit />
                </el-icon>
                <el-icon @click='listItemDelete(state,scope.row.id)' style='cursor: pointer;font-size: 18px;top:2px;margin-left: 10px;color: #ED6F6F'>
                  <Delete />
                </el-icon>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
              @size-change='listQuery(state)' @current-change='listQuery(state)'
              class='mt8' :pager-count='5' :page-sizes='[10, 20, 30]' background
              :total='state.total' v-model:current-page='state.form.page' v-model:page-size='state.form.pageSize'
              layout='total, sizes, prev, pager, next, jumper'
          />

        </el-card>
        <Medit ref='editRef' @close='listQuery(state)' />
      </pane>
    </splitpanes>
  </Wrap>
</template>
<script lang='ts'>
export default { name: 'SysOrgUser' };
</script>
<script lang='ts' setup>
import { Search, Plus, Delete, ArrowDown, ArrowUp, Edit } from '@element-plus/icons-vue';
import { onMounted, reactive, ref } from 'vue';
import { listQuery, listDelete, listSelect, tabAdd, tabEdit, listItemDelete } from '/@/comps/page/index';
import Wrap from '/@/comps/page/Wrap.vue';
import DeptTree from '/@/comps/sys/DeptTree.vue';
import Medit from './medit.vue';
import { Splitpanes, Pane } from 'splitpanes';
import 'splitpanes/dist/splitpanes.css';

const state = reactive({
  url: '/sys/org/user', loading: true, ids: [], moreParams: false,
  form: {} as any, single: true, multiple: true, list: [], total: 0,
  pageShow: false, leftPaneSize: 250 / (window.innerWidth - 220) * 100,
});

const editRef = ref() as any;

onMounted(() => {
  state.pageShow = true;
  listQuery(state);
});

const flush = async () => {
  await listQuery(state);
};

//region a 左侧部门树点击
const nodeClick = async (node: any) => {
  state.form.depid = node.id;
  state.form.depna = node.name;
  await listQuery(state);
};
//endregion
</script>



<template>
  <div >
    <el-card class='box-card'>
      <template #header>
        <div class='zjustify'>
          <div>
            <el-input v-model='state.form.name' placeholder='输入名称回车查询' class='list-search' clearable
                      @keyup.enter='listQuery(state)'/>
            <el-button type='primary' @click='listQuery(state)' plain>查 询</el-button>
            <el-button class='more-button' :icon='state.moreParams?ArrowUp:ArrowDown' plain
                       @click='state.moreParams=!state.moreParams'/>
          </div>
          <div>
            <el-button type='success' :icon='Plus' @click='editRef.open({})' plain>新增</el-button>
            <el-button type='success' :icon='Download' @click='toFinish' plain>导出</el-button>
            <el-button type='danger' :icon='Delete' :disabled='state.multiple' @click='listDelete(state)' plain>删除
            </el-button>
          </div>
        </div>
        <div v-show='state.moreParams' class='more-params'>
          <el-form :inline='true' label-width='100px'>
            <el-form-item label='更多参数1'>
              <el-input v-model='state.form.xxx' placeholder='更多参数1'/>
            </el-form-item>
            <el-form-item label='更多参数2'>
              <el-input v-model='state.form.yyy' placeholder='更多参数2'/>
            </el-form-item>
            <el-form-item/>
          </el-form>
        </div>
      </template>
      <el-table height='400' :cell-style="{padding:'2px'}" :row-style="{height: '36px'}"
                v-loading='state.loading' :data='state.list'
                border stripe @selection-change='listSelect($event,state)'>
        <el-table-column type='selection' width='55' align='center'/>
        <el-table-column label='id' prop='id' width='160'>
          <template #default='scope'>
		    <span style='cursor:pointer;color: #3e9ece' @click='editRef.open({id:scope.row.id})'>
              {{ scope.row.id }}
            </span>
          </template>
        </el-table-column>

        <el-table-column label="名称" prop="name"/>
        <el-table-column label="年龄" prop="age"/>
        <el-table-column label="创建人" prop="createBy"/>
        <el-table-column label="创建时间" prop="createTime"/>
        <el-table-column label="修改人" prop="updateBy"/>
        <el-table-column label="修改时间" prop="updateTime"/>

      </el-table>

      <el-pagination
          @size-change='listQuery(state)' @current-change='listQuery(state)'
          class='mt8' :pager-count='5' :page-sizes='[10, 20, 30]' background
          :total='state.total' v-model:current-page='state.form.current'
          v-model:page-size='state.form.pageSize'
          layout='total, sizes, prev, pager, next, jumper'
      />
    </el-card>
    <vxe-grid ref='xGrid' v-bind="gridOptions"></vxe-grid>
    <Pedit ref="editRef" @close="listQuery(state)"/>
  </div>
</template>

<script lang='ts' setup>
import {Plus, Delete, Download, ArrowDown, ArrowUp} from '@element-plus/icons-vue';
import {onMounted, reactive, ref} from 'vue';
import {listQuery, listDelete, listSelect} from '/@/comps/page/index';
import Pedit from './edit.vue';
import {useMenuApi} from "/@/api/menu";
import {VXETable, VxeGridInstance, VxeGridProps} from 'vxe-table'

const xGrid = ref<VxeGridInstance>();

const editRef = ref() as any;
const state = reactive({
  url: '/ceshi', loading: true, ids: [],
  form: {}, single: true, multiple: true, list: [], total: 0,
});
const menuApi = useMenuApi();
const toFinish = () => {
  menuApi.exportExcel()
};

const gridOptions = reactive<VxeGridProps>({
  border: true,
  showHeaderOverflow: true,
  showOverflow: true,
  keepSource: true,
  id: 'full_edit_1',
  height: 600,
  rowConfig: {
    keyField: 'id',
    isHover: true
  },
  columnConfig: {
    resizable: true
  },
  customConfig: {
    storage: true,
    checkMethod ({ column }) {
      if (['nickname', 'role'].includes(column.field)) {
        return false
      }
      return true
    }
  },
  printConfig: {
    columns: [
      { field: 'name' },
      { field: 'email' },
      { field: 'nickname' },
      { field: 'age' },
      { field: 'amount' }
    ]
  },
  sortConfig: {
    trigger: 'cell',
    remote: true
  },
  filterConfig: {
    remote: true
  },
  pagerConfig: {
    pageSize: 10,
    pageSizes: [5, 10, 15, 20, 50, 100, 200, 500, 1000]
  },
  formConfig: {
    titleWidth: 100,
    titleAlign: 'right',
    items: [
      { field: 'cscscs', title: 'app.body.label.name', span: 8, titlePrefix: { message: 'app.body.valid.rName', icon: 'vxe-icon-question-circle-fill' }, itemRender: { name: '$input', props: { placeholder: '请输入名称' } } },
      { field: 'email', title: '邮件', span: 8, titlePrefix: { useHTML: true, message: '点击链接：<a class="link" href="https://vxetable.cn" target="_blank">vxe-table官网</a>', icon: 'vxe-icon-question-circle-fill' }, itemRender: { name: '$input', props: { placeholder: '请输入邮件' } } },
      { field: 'nickname', title: '昵称', span: 8, itemRender: { name: '$input', props: { placeholder: '请输入昵称' } } },
      { field: 'role', title: '角色', span: 8, folding: true, itemRender: { name: '$input', props: { placeholder: '请输入角色' } } },
      { field: 'sex', title: '性别', span: 8, folding: true, titleSuffix: { message: '注意，必填信息！', icon: 'vxe-icon-question-circle-fill' }, itemRender: { name: '$select', options: [] } },
      { field: 'age', title: '年龄', span: 8, folding: true, itemRender: { name: '$input', props: { type: 'number', min: 1, max: 120, placeholder: '请输入年龄' } } },
      { span: 24, align: 'center', collapseNode: true, itemRender: { name: '$buttons', children: [{ props: { type: 'submit', content: 'app.body.label.search', status: 'primary' } }, { props: { type: 'reset', content: 'app.body.label.reset' } }] } }
    ]
  },
  toolbarConfig: {
    buttons: [
      { code: 'insert_actived', name: '新增' },
      { code: 'delete', name: '直接删除' },
      { code: 'mark_cancel', name: '删除/取消' },
      { code: 'save', name: 'app.body.button.save', status: 'success' }
    ],
    refresh: true,
    import: true,
    export: true,
    print: true,
    zoom: true,
    custom: true
  },
  proxyConfig: {
    seq: true, // 启用动态序号代理，每一页的序号会根据当前页数变化
    sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
    filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为
    form: true, // 启用表单代理，当点击表单提交按钮时会自动触发 reload 行为
    // 对应响应结果 { result: [], page: { total: 100 } }
    props: {
      result: 'result', // 配置响应结果列表字段
      total: 'page.total' // 配置响应结果总页数字段
    },
    // 只接收Promise，具体实现自由发挥
    ajax: {
      // 当点击工具栏查询按钮或者手动提交指令 query或reload 时会被触发
      query: ({ page, sorts, filters, form }) => {
        const queryParams: any = Object.assign({}, form)
        // 处理排序条件
        const firstSort = sorts[0]
        if (firstSort) {
          queryParams.sort = firstSort.field
          queryParams.order = firstSort.order
        }
        // 处理筛选条件
        filters.forEach(({ field, values }) => {
          queryParams[field] = values.join(',')
        })
        state.form=form
        listQuery(state)
        return
      },
      // 当点击工具栏删除按钮或者手动提交指令 delete 时会被触发
      delete: ({ body }) => {
        listDelete(state)
        return
      },
      // 当点击工具栏保存按钮或者手动提交指令 save 时会被触发
      save: ({ body }) => {
        editRef.open({})
        return
      }
    }
  },
  columns: [
    { type: 'checkbox', title: 'ID', width: 120 },
    { field: 'name', title: 'Name', sortable: true, titlePrefix: { message: '名称必须填写！' }, editRender: { name: 'input', attrs: { placeholder: '请输入名称' } } },
    {
      field: 'role',
      title: 'Role',
      sortable: true,
      titlePrefix: { useHTML: true, content: '点击链接：<a class="link" href="https://vxetable.cn" target="_blank">vxe-table官网</a>' },
      filters: [
        { label: '前端开发', value: '前端' },
        { label: '后端开发', value: '后端' },
        { label: '测试', value: '测试' },
        { label: '程序员鼓励师', value: '程序员鼓励师' }
      ],
      filterMultiple: false,
      editRender: { name: 'input', attrs: { placeholder: '请输入角色' } }
    },
    { field: 'email', title: 'Email', width: 160, editRender: { name: '$input', props: { placeholder: '请输入邮件' } } },
    { field: 'nickname', title: 'Nickname', editRender: { name: 'input', attrs: { placeholder: '请输入昵称' } } },
    {
      field: 'sex',
      title: 'Sex',
      filters: [
        { label: '男', value: '1' },
        { label: '女', value: '0' }
      ],
      editRender: { name: '$select', options: [], props: { placeholder: '请选择性别' } }
    },
    { field: 'age', title: 'Age', visible: false, sortable: true, editRender: { name: '$input', props: { type: 'number', min: 1, max: 120 } } },
    {
      field: 'amount',
      title: 'Amount',
      formatter ({ cellValue }) {
        return cellValue ? `￥${XEUtils.commafy(XEUtils.toNumber(cellValue), { digits: 2 })}` : ''
      },
      editRender:
          { name: '$input', props: { type: 'float', digits: 2, placeholder: '请输入数值' } }
    },
    {
      field: 'updateDate',
      title: 'Update Date',
      width: 160,
      visible: false,
      sortable: true,
      formatter ({ cellValue }) {
        return XEUtils.toDateString(cellValue, 'yyyy-MM-dd HH:ss:mm')
      }
    },
    {
      field: 'createDate',
      title: 'Create Date',
      width: 160,
      visible: false,
      sortable: true,
      formatter ({ cellValue }) {
        return XEUtils.toDateString(cellValue, 'yyyy-MM-dd')
      }
    }
  ],
  importConfig: {
    remote: true,
    types: ['xlsx'],
    modes: ['insert'],
    // 自定义服务端导入
    importMethod ({ file }) {
      const $grid = xGrid.value
      const formBody = new FormData()
      formBody.append('file', file)
      return fetch(`${serveApiUrl.value}/api/pub/import`, { method: 'POST', body: formBody }).then(response => response.json()).then(data => {
        VXETable.modal.message({ content: `成功导入 ${data.result.insertRows} 条记录！`, status: 'success' })
        // 导入完成，刷新表格
        $grid.commitProxy('query')
      }).catch(() => {
        VXETable.modal.message({ content: '导入失败，请检查数据是否正确！', status: 'error' })
      })
    }
  },
  exportConfig: {
    remote: true,
    types: ['xlsx'],
    modes: ['current', 'selected', 'all'],
    // 自定义服务端导出
    exportMethod ({ options }) {
      const $grid = xGrid.value
      const proxyInfo = $grid.getProxyInfo()
      // 传给服务端的参数
      const body = {
        filename: options.filename,
        sheetName: options.sheetName,
        isHeader: options.isHeader,
        original: options.original,
        mode: options.mode,
        pager: proxyInfo ? proxyInfo.pager : null,
        ids: options.mode === 'selected' ? options.data.map((item) => item.id) : [],
        fields: options.columns.map((column) => {
          return {
            field: column.field,
            title: column.title
          }
        })
      }
      // 开始服务端导出
      return fetch(`${serveApiUrl.value}/api/pub/export`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }).then(response => response.json()).then(data => {
        if (data.id) {
          VXETable.modal.message({ content: '导出成功，开始下载', status: 'success' })
          // 读取路径，请求文件
          fetch(`${serveApiUrl.value}/api/pub/export/download/${data.id}`).then(response => {
            response.blob().then(blob => {
              // 开始下载
              VXETable.saveFile({ filename: '导出数据', type: 'xlsx', content: blob })
            })
          })
        }
      }).catch(() => {
        VXETable.modal.message({ content: '导出失败！', status: 'error' })
      })
    }
  },
  checkboxConfig: {
    labelField: 'id',
    reserve: true,
    highlight: true,
    range: true
  },
  editRules: {
    name: [
      { required: true, message: 'app.body.valid.rName' },
      { min: 3, max: 50, message: '名称长度在 3 到 50 个字符' }
    ],
    email: [
      { required: true, message: '邮件必须填写' }
    ],
    role: [
      { required: true, message: '角色必须填写' }
    ]
  },
  editConfig: {
    trigger: 'click',
    mode: 'row',
    showStatus: true
  }
})

onMounted(() => {
  listQuery(state);
});
</script>

